/**
 * Project Name:kany-utils
 * File Name:OptionFormat.java
 * Package Name:me.kany.utils.config.ini
 * Date:2016-1-7上午11:07:17
 * Copyright (c) 2016, Jason.Wang All Rights Reserved.
 *
*/

package me.kany.utils.config.ini.option;
/**
 * ClassName:OptionFormat <br/>
 * Function: INI文件项的格式. <br/>
 * Date:     2016-1-7 上午11:07:17 <br/>
 * @author   Jason.Wang
 * @version  
 * @since    JDK 1.7
 * @see 	 
 */
public class OptionFormat {

    private static final int EXPECTED_TOKENS = 4;

    private String[] formatTokens;

    public OptionFormat(String formatString) {
        this.formatTokens = this.compileFormat(formatString);
    }

    public String format(String name, String value, char separator) {
        String[] t = this.formatTokens;
        return t[0] + name + t[1] + separator + t[2] + value + t[3];
    }

    private String[] compileFormat(String formatString) {
        String[] tokens = {"", "", "", ""};
        int tokenCount = 0;
        boolean seenPercent = false;
        StringBuffer token = new StringBuffer();
        for (int i = 0; i < formatString.length(); i++) {
            switch (formatString.charAt(i)) {
                case '%':
                    if (seenPercent) {
                        token.append("%");
                        seenPercent = false;
                    }
                    else {
                        seenPercent = true;
                    }
                    break;
                case 's':
                    if (seenPercent) {
                        if (tokenCount >= EXPECTED_TOKENS) {
                            throw new IllegalArgumentException(
                                "Illegal option format. Too many %s placeholders.");
                        }
                        tokens[tokenCount] = token.toString();
                        tokenCount++;
                        token = new StringBuffer();
                        seenPercent = false;
                    }
                    else {
                        token.append("s");
                    }
                    break;
                default:
                    if (seenPercent) {
                        throw new IllegalArgumentException(
                            "Illegal option format. Unknown format specifier.");
                    }
                    token.append(formatString.charAt(i));
                    break;
            }
        }
        if (tokenCount != EXPECTED_TOKENS - 1) {
            throw new IllegalArgumentException(
                    "Illegal option format. Not enough %s placeholders.");
        }
        tokens[tokenCount] = token.toString();
        return tokens;
    }

}
